import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _class, _class2;

/**
 * template - 通用导入主页面
 * @since 2019-1-28
 * @version 0.0.1

 */
import React, { PureComponent } from 'react';
import { Button, Card, Col, Form, Input, Row, Select, Modal } from 'antd';
import { connect } from 'dva';
import { Bind } from 'lodash-decorators';
import classNames from 'classnames';
import { Content, Header } from 'components/Page';
import Lov from 'components/Lov';
import Switch from 'components/Switch';
import Upload from 'components/Upload/UploadButton';
import notification from 'utils/notification';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import { getCurrentOrganizationId, getEditTableData, isTenantRoleLevel } from 'utils/utils';
import { CODE_UPPER } from 'utils/regExp';
import { DETAIL_CARD_CLASSNAME, DETAIL_CARD_TABLE_CLASSNAME, EDIT_FORM_ITEM_LAYOUT, EDIT_FORM_ROW_LAYOUT, FORM_COL_3_LAYOUT } from 'utils/constants';
import { BKT_CIMP } from 'utils/config';
import styles from "./index.less?modules";
import SheetTable from "./SheetTable";
var Option = Select.Option;
/**
 * Form.Item 组件label、wrapper长度比例划分
 */

/**
 * 通用模板行页面
 * @extends {Component} - React.Component
 * @reactProps {Object} form - 表单对象
 * @reactProps {Function} [dispatch=function(e) {return e;}] - redux dispatch方法
 * @return React.element
 */

var Detail = (_dec = connect(function (_ref) {
  var template = _ref.template,
      loading = _ref.loading;
  return {
    template: template,
    detailLoading: loading.effects['template/queryOneHeader'],
    saveLoading: loading.effects['template/update'] || loading.effects['template/create'],
    organizationId: getCurrentOrganizationId()
  };
}), _dec2 = Form.create({
  fieldNameProp: null
}), _dec3 = formatterCollections({
  code: ['cimp.template', 'entity.template']
}), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = /*#__PURE__*/function (_PureComponent) {
  _inherits(Detail, _PureComponent);

  var _super = _createSuper(Detail);

  function Detail() {
    var _this;

    _classCallCheck(this, Detail);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      templateTypeCode: ''
    };
    _this.ref = React.createRef();
    return _this;
  }

  _createClass(Detail, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.queryHeader();
      var dispatch = this.props.dispatch;
      var lovCodes = {
        typeList: 'CIMP.TEMPLATE.TEMPLATETYPE',
        sheetList: 'CIMP.IMPORT_SHEET'
      };
      dispatch({
        type: 'template/init',
        payload: {
          lovCodes: lovCodes
        }
      });
    }
  }, {
    key: "queryHeader",
    value: function queryHeader() {
      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          match = _this$props.match,
          organizationId = _this$props.organizationId;
      var id = match.params.id;

      if (id !== 'create') {
        dispatch({
          type: 'template/queryOneHeader',
          payload: {
            templateId: id,
            organizationId: organizationId
          }
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.props.dispatch({
        type: 'template/updateState',
        payload: {
          headerData: {},
          templateTargetList: []
        }
      });
    }
    /**
     * 保存，验证头数据和sheet行数据
     */

  }, {
    key: "save",
    value: function save() {
      var _this2 = this;

      var _this$props2 = this.props,
          form = _this$props2.form,
          template = _this$props2.template;
      var _template$headerData = template.headerData,
          headerData = _template$headerData === void 0 ? {} : _template$headerData,
          _template$templateTar = template.templateTargetList,
          templateTargetList = _template$templateTar === void 0 ? [] : _template$templateTar;
      var editList = templateTargetList.filter(function (item) {
        return item._status === 'create' || item._status === 'update';
      });
      var params = getEditTableData(templateTargetList, ['id']);
      form.validateFields(function (err, values) {
        if (headerData.templateUrl && values.templateUrl === headerData.templateUrl) {
          Modal.info({
            title: intl.get('cimp.template.message.confirm.syncTemplate').d('请同步调整自定义模板'),
            onOk: function onOk() {
              _this2.sendRequest(err, values, params, editList, headerData);
            },
            okText: intl.get('cpaas.common.button.ok').d('确定')
          });
        } else {
          _this2.sendRequest(err, values, params, editList, headerData);
        }
      });
    }
    /**
     * 发送保存请求
     * @param {object} err
     * @param {object} values
     * @param {object} params
     * @param {array} editList
     * @param {object} headerData
     * @memberof Detail
     */

  }, {
    key: "sendRequest",
    value: function sendRequest(err, values, params, editList, headerData) {
      var _this3 = this;

      var _this$props3 = this.props,
          dispatch = _this$props3.dispatch,
          history = _this$props3.history,
          match = _this$props3.match;
      var id = match.params.id;

      if (!err) {
        // 可以单独保存头数据
        if (Array.isArray(params) && editList.length > 0) {
          if (params.length > 0) {
            dispatch({
              type: "template/".concat(headerData.id !== undefined ? 'update' : 'create'),
              payload: _objectSpread(_objectSpread(_objectSpread({}, headerData), values), {}, {
                templateTargetList: params
              })
            }).then(function (res) {
              if (res) {
                notification.success();

                if (id === 'create') {
                  history.push("/cimp/template/detail/".concat(res.id));

                  _this3.queryHeader();
                } else {
                  _this3.queryHeader();
                }
              }
            });
          }
        } else {
          dispatch({
            type: "template/".concat(headerData.id !== undefined ? 'update' : 'create'),
            payload: _objectSpread(_objectSpread({}, headerData), values)
          }).then(function (res) {
            if (res) {
              notification.success();

              if (id === 'create') {
                history.push("/cimp/template/detail/".concat(res.id));
              } else {
                _this3.queryHeader();
              }
            }
          });
        }
      } else {
        this.ref.current.forceUpdate();
      }
    }
    /**
     * 上传文件成功时调用
     * @param {object} file
     */

  }, {
    key: "onUploadSuccess",
    value: function onUploadSuccess(file) {
      var form = this.props.form;

      if (file) {
        form.setFieldsValue({
          templateUrl: file.response
        });
      }
    }
    /**
     * 删除文件后调用
     * @param {object} file
     */

  }, {
    key: "onCancelSuccess",
    value: function onCancelSuccess(file) {
      var form = this.props.form;

      if (file) {
        form.setFieldsValue({
          templateUrl: ''
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$props4 = this.props,
          _this$props4$detailLo = _this$props4.detailLoading,
          detailLoading = _this$props4$detailLo === void 0 ? false : _this$props4$detailLo,
          _this$props4$saveLoad = _this$props4.saveLoading,
          saveLoading = _this$props4$saveLoad === void 0 ? false : _this$props4$saveLoad,
          _this$props4$form = _this$props4.form,
          getFieldDecorator = _this$props4$form.getFieldDecorator,
          getFieldValue = _this$props4$form.getFieldValue,
          setFieldsValue = _this$props4$form.setFieldsValue,
          template = _this$props4.template,
          match = _this$props4.match;
      var templateTypeCode = this.state.templateTypeCode;
      var id = match.params.id;
      var headerData = template.headerData,
          _template$code = template.code,
          code = _template$code === void 0 ? {} : _template$code,
          _template$templateTar2 = template.templateTargetList,
          templateTargetList = _template$templateTar2 === void 0 ? [] : _template$templateTar2;
      var templateCode = headerData.templateCode,
          description = headerData.description,
          enabledFlag = headerData.enabledFlag,
          fragmentFlag = headerData.fragmentFlag,
          prefixPatch = headerData.prefixPatch,
          tenantId = headerData.tenantId,
          tenantName = headerData.tenantName,
          templateUrl = headerData.templateUrl,
          templateFileName = headerData.templateFileName,
          _headerData$templateN = headerData.templateName,
          templateName = _headerData$templateN === void 0 ? '' : _headerData$templateN,
          _headerData$templateT = headerData.templateType,
          templateType = _headerData$templateT === void 0 ? 'C' : _headerData$templateT;
      var fileList = templateUrl ? [{
        uid: '-1',
        name: templateFileName,
        status: 'done',
        url: templateUrl
      }] : [];
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Header, {
        title: intl.get("cimp.template.view.message.title.templateDetail").d('导入模板管理明细'),
        backPath: "/cimp/template/list"
      }, /*#__PURE__*/React.createElement(Button, {
        onClick: this.save,
        type: "primary",
        icon: "save",
        loading: saveLoading
      }, intl.get('cpaas.common.button.save').d('保存'))), /*#__PURE__*/React.createElement(Content, null, /*#__PURE__*/React.createElement(Card, {
        key: "import-template-header",
        bordered: false,
        className: DETAIL_CARD_CLASSNAME,
        loading: detailLoading,
        title: /*#__PURE__*/React.createElement("h3", null, intl.get("cimp.template.view.message.title.commonTemplate").d('通用导入'))
      }, /*#__PURE__*/React.createElement(Form, {
        className: classNames('more-fields-search-form', styles['template-form'])
      }, !isTenantRoleLevel() && /*#__PURE__*/React.createElement(Row, EDIT_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get('cimp.template.model.template.tenantName').d('租户')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('tenantId', {
        initialValue: tenantId,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get('cimp.template.model.template.tenantName').d('租户')
          })
        }]
      })(match.params.id !== 'create' ? /*#__PURE__*/React.createElement(React.Fragment, null, tenantName) : /*#__PURE__*/React.createElement(Lov, {
        textValue: tenantName,
        code: "CPFM.TENANT"
      }))))), /*#__PURE__*/React.createElement(Row, EDIT_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("entity.template.name").d('模板名称')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('templateName', {
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get("entity.template.name").d('模板名称')
          })
        }],
        initialValue: templateName
      })( /*#__PURE__*/React.createElement(Input, null)))), /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("entity.template.code").d('模板代码')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('templateCode', {
        initialValue: templateCode,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get("entity.template.code").d('模板代码')
          })
        }, {
          pattern: CODE_UPPER,
          message: intl.get('cpaas.common.validation.codeUpper').d('全大写及数字，必须以字母、数字开头，可包含“-”、“_”、“.”、“/”')
        }, {
          max: 30,
          message: intl.get('cpaas.common.validation.max', {
            max: 30
          })
        }]
      })(match.params.id !== 'create' ? /*#__PURE__*/React.createElement(React.Fragment, null, templateCode) : /*#__PURE__*/React.createElement(Input, {
        trim: true,
        typeCase: "upper",
        inputChinese: false
      })))), /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("entity.template.type").d('模板类型')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('templateType', {
        rules: [{
          required: true,
          message: intl.get("cpaas.common.validation.notNull", {
            name: intl.get("entity.template.type").d('模板类型')
          })
        }],
        initialValue: templateType
      })( /*#__PURE__*/React.createElement(Select, {
        onChange: function onChange(val) {
          _this4.setState({
            templateTypeCode: val
          });

          if (val === 'S') {
            setFieldsValue({
              prefixPatch: ''
            });
          }
        },
        disabled: templateTargetList.length > 0
      }, (code['CIMP.TEMPLATE.TEMPLATETYPE'] || []).map(function (n) {
        return /*#__PURE__*/React.createElement(Option, {
          key: n.value,
          value: n.value
        }, n.meaning);
      })))))), /*#__PURE__*/React.createElement(Row, EDIT_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("cimp.template.model.template.prefixPatch").d('客户端路径前缀')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('prefixPatch', {
        rules: [{
          required: getFieldValue('templateType') === 'C',
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get('cimp.template.model.template.prefixPatch').d('客户端路径前缀')
          })
        }],
        initialValue: prefixPatch
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: getFieldValue('templateType') !== 'C'
      })))), /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("cimp.template.model.template.description").d('描述')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('description', {
        initialValue: description
      })( /*#__PURE__*/React.createElement(Input, null)))), /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("cimp.template.model.template.piece").d('分片')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('fragmentFlag', {
        initialValue: match.params.id === 'create' ? 0 : fragmentFlag
      })( /*#__PURE__*/React.createElement(Switch, null))))), /*#__PURE__*/React.createElement(Row, EDIT_FORM_ROW_LAYOUT, /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("cimp.template.model.template.customTemplate").d('自定义模板')
      }, EDIT_FORM_ITEM_LAYOUT), /*#__PURE__*/React.createElement(Upload, {
        accept: ".xlsx",
        single: true,
        fileList: fileList,
        bucketName: BKT_CIMP,
        bucketDirectory: "cimp01",
        onUploadSuccess: this.onUploadSuccess,
        onRemove: this.onCancelSuccess
      })), /*#__PURE__*/React.createElement(Form.Item, EDIT_FORM_ITEM_LAYOUT, getFieldDecorator('templateUrl', {
        initialValue: templateUrl
      })( /*#__PURE__*/React.createElement("div", null)))), /*#__PURE__*/React.createElement(Col, FORM_COL_3_LAYOUT, /*#__PURE__*/React.createElement(Form.Item, Object.assign({
        label: intl.get("cpaas.common.status.enable").d('启用')
      }, EDIT_FORM_ITEM_LAYOUT), getFieldDecorator('enabledFlag', {
        initialValue: match.params.id === 'create' ? 1 : enabledFlag
      })( /*#__PURE__*/React.createElement(Switch, null))))))), /*#__PURE__*/React.createElement(Card, {
        key: "import-template-line",
        bordered: false,
        className: DETAIL_CARD_TABLE_CLASSNAME,
        title: /*#__PURE__*/React.createElement("h3", null, intl.get("cimp.template.view.message.title.sheetTitle").d('Sheet页'))
      }, /*#__PURE__*/React.createElement(SheetTable, {
        ref: this.ref,
        loading: detailLoading,
        templateType: templateTypeCode || templateType,
        detailId: id
      }))));
    }
  }]);

  return Detail;
}(PureComponent), (_applyDecoratedDescriptor(_class2.prototype, "save", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "save"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "sendRequest", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "sendRequest"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onUploadSuccess", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "onUploadSuccess"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onCancelSuccess", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "onCancelSuccess"), _class2.prototype)), _class2)) || _class) || _class) || _class);
export { Detail as default };